package com.sniper;

import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ClassUtils;

import java.util.Objects;


/**
 * 网关
 * 打包的时候无法吧动态路由文件打包进去
 *
 * @author suzhen
 */
@EnableZuulProxy
@SpringCloudApplication
//@EnableConfigurationProperties({FilterConfiguration.class})
public class ServiceZuulApplication {

    private static Logger logger = LoggerFactory.getLogger(ServiceZuulApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }

    /**
     * 给多有的服务增加默认路由，匹配名称和版本，并颠倒
     *
     * @return
     */
    @Bean
    public PatternServiceRouteMapper serviceRouteMapper() {
        return new PatternServiceRouteMapper(
                "(?<name>^.+)-(?<version>v.+$)",
                "${version}/${name}");
    }

    @Bean
    @RefreshScope
    @ConfigurationProperties("zuul")
    public ZuulProperties zuulProperties() {
        return new ZuulProperties();
    }

    /**
     * 动态加载过滤器
     *
     * @param filterConfiguration
     * @return
     */
    //@Bean
    public FilterLoader filterLoader(FilterConfiguration filterConfiguration) {
        FilterLoader filterLoader = FilterLoader.getInstance();
        filterLoader.setCompiler(new GroovyCompiler());

        //Users/suzhen/approot/web/spring-cloud-1.5.11/service-zuul/target/classes/com/sniper/filter
        //Users/suzhen/approot/web/spring-cloud-1.5.11/service-zuul/target/classes/com/sniper/filter/pre
        String appDir = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("")).getPath();
        logger.debug("appDir: {}", appDir);
        System.out.println(appDir);
        try {
            FilterFileManager.setFilenameFilter(new GroovyFileFilter());
            FilterFileManager.init(
                    filterConfiguration.getInterval(),
                    appDir + filterConfiguration.getRoot() + "/pre",
                    appDir + filterConfiguration.getRoot() + "/post");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return filterLoader;
    }
}